package com.atguigu.gmall.payment.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author: atguigu
 * @create: 2023-01-28 16:19
 */
@RestController
@RequestMapping("/api/payment/alipay")
public class AlipayController {

    @Autowired
    private AlipayService alipayService;

    /**
     * 生成支付宝支付页面；保存本地交易记录
     * @param orderId 订单ID
     * @return
     */
    @GetMapping("/submit/{orderId}")
    public String createAlipayForm(@PathVariable("orderId") Long orderId){
        return alipayService.createAlipayForm(orderId);
    }

    /**
     * 处理支付宝支付页面同步回调
     */
    @GetMapping("/callback/return")
    public void returnPaySuccessPage(HttpServletResponse response) throws IOException {
        //重定向到支付成功页面
        response.sendRedirect(AlipayConfig.return_order_url);
    }


    /**
     * 处理用户支付成功后-支付宝提交异步回调
     * @param paramsMap
     * @return
     */
    @PostMapping("/callback/notify")
    public String payResultNofity(@RequestParam Map<String, String> paramsMap){
        return alipayService.payResultNofity(paramsMap);
    }



    /**
     * 发起退款
     * @param orderId
     * @return
     */
    @GetMapping("refund/{orderId}")
    public Result refund(@PathVariable(value = "orderId")Long orderId) {
        // 调用退款接口
        boolean flag = alipayService.refund(orderId);
        return Result.ok(flag);
    }



    /**
     * 根据订单ID关闭支付宝交易记录
     * @param orderId 订单ID
     * @return
     */
    @GetMapping("closePay/{orderId}")
    public Boolean closePay(@PathVariable Long orderId){
        Boolean aBoolean = alipayService.closePay(orderId);
        return aBoolean;
    }



    /**
     * 查看是否有交易记录
     * @param orderId
     * @return
     */
    @GetMapping("checkPayment/{orderId}")
    public Boolean checkPayment(@PathVariable Long orderId){
        // 调用退款接口
        boolean flag = alipayService.checkPayment(orderId);
        return flag;
    }
}
